package com.dorm.cj.extension.handlerMethodArgumentResolver;

import com.dorm.cj.common.User;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
@Component
public class CurrentUserResolver implements HandlerMethodArgumentResolver {


    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        //从请求头取出信息绑定到注解对应的参数上，这个信息可以是发起请求带上的，也可以是拦截器根据塞的值，具体使用看场景
        //一般场景：请求带token->HandlerInterceptorAdapter将token转成currentuser,并塞到请求头->HandlerMethodArgumentResolver处理参数绑定
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        Long userId = Long.valueOf(request.getHeader("userId"));
        User user = new User();
        user.setId(userId);
        return user;

    }
}
